<?php

namespace App\Urls;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Route;

class UrlPresenter
{
    public function __construct(public Model $model)
    {
        //
    }

    public function __get($key)
    {
        if (method_exists($this, $key)) {
            return $this->$key();
        }

        return $this->$key;
    }

    public function show(array $params = []): string
    {
        return $this->link('show', $params);
    }

    public function link(string $name, array $params = []): string
    {
        // 将模型id放入第一个参数
        array_unshift($params, $this->model->getRouteKey());

        $route_name = sprintf('%s.%s', $this->model->getTable(), $name);

        if (! Route::has($route_name)) {
            return '';
        }

        return route($route_name, $params);
    }

    public function edit(array $params = []): string
    {
        return $this->link('edit', $params);
    }

    public function update(array $params = []): string
    {
        return $this->link('update', $params);
    }

    public function delete(array $params = []): string
    {
        return $this->link('destroy', $params);
    }
}
